package com.windward.vii.service;

import com.alibaba.fastjson.JSONObject;
import com.windward.vii.common.JsonResult;
import com.windward.vii.dao.entity.AppRecord;
import com.windward.vii.dao.mapper.AppRecordMapper;
import com.windward.vii.utils.StringUtils;
import com.windward.vii.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by tiansj on 2017/9/28.
 */
@Component
public class AppRecordService {

    private static Logger logger = LoggerFactory.getLogger(AppRecordService.class);

    @Resource
    AppRecordMapper appRecordMapper;
    
    public JsonResult checkUpdate(Integer appType, Integer versionCode) {
        JSONObject object = new JSONObject();
        // 查询比versionCode大的版本号
        AppRecord appRecord = appRecordMapper.selectNewVersion(appType, versionCode);
        if(appRecord != null && appRecord.getForceUpdate()) {
            object.put("forceUpdate", true);
        } else {
            object.put("forceUpdate", false);
        }
        JsonResult jsonResult = JsonResult.success();
        jsonResult.setBody(object);
        return jsonResult;
    }


    public boolean checkIsInReview(String httpUserAgent) {
        String versionName = "";
        if(StringUtils.isNotEmpty(httpUserAgent)) {
            if(httpUserAgent.contains("iOS")) {
                String[] arr = httpUserAgent.split(" ");
                String first = arr[0];
                if(first != null) {
                    String[] firstArr = first.split("/");
                    if(firstArr.length > 1) {
                        versionName = firstArr[1];
                    }
                }
            }
        }
        logger.info("getAppVersionFromUserAgent={}", versionName);
        if(StringUtils.isBlank(versionName)) {
            return false;
        }

        AppRecord appRecord = appRecordMapper.selectIosInReviewRecord(versionName);
        return appRecord != null;
    }
    
}
